package com.sakila.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sakila.dao.FilmDao;
import com.sakila.pojo.Category;
import com.sakila.pojo.Film;
import com.sakila.pojo.other.Page;
import com.sakila.service.FilmService;
import com.sakila.service.util.SortListUtil;
import com.sakila.vo.FilmVo;

@Service
public class FilmServiceImpl implements FilmService {
	@Resource
	private FilmDao filmDao;
	
	public FilmVo findAll(Page page) {
		List<Film> list = filmDao.findAll(page);
		Long totalNumOfRows = filmDao.getTotalNumOfRows();
		return new FilmVo(list, totalNumOfRows);
	}
	
	public Long getTotalNumOfRows() {
		return filmDao.getTotalNumOfRows();
	}

	@Override
	public FilmVo sortFilms(Page page, String order, String sortItem) {
		
		//obtain data from cache
		List<Film> list = filmDao.findAll(page);
		SortListUtil.sort(list, order, sortItem);
		Long totalNumOfRows = filmDao.getTotalNumOfRows();
		return new FilmVo(list, totalNumOfRows);
	}


	@Override
	public FilmVo sortFilms(Page page, String order, String sortItem,
							String titleName, String actorName, Integer categoryId) {
		FilmVo filmVo = this.findByTitleOrActorOrCategory(page, titleName, actorName, categoryId);
		SortListUtil.sort(filmVo.getList(), order, sortItem);
		return filmVo;
	}
	
	@Override
	public FilmVo findByTitleOrActorOrCategory(Page page, String titleName,
			String actorName, Integer categoryId) {
		Film film = createFilm(titleName, categoryId);
		List<Film> list = filmDao.findByPropertiesAndActor(page, film, actorName);
		Long totalNumOfRow = filmDao.getTotalNumOfRowsByPropertiesAndActor(film, actorName);
		return new FilmVo(list, totalNumOfRow);
	}

	@Override
	public Long getTotalNumOfRowsByPropertiesAndActor(String titleName,
			String actorName, Integer categoryId) {
		Film film = createFilm(titleName, categoryId);
		return filmDao.getTotalNumOfRowsByPropertiesAndActor(film, actorName);
	}
	
	private Film createFilm(String titleName, Integer categoryId) {
		Film film = new Film();
		film.setTitle(titleName);
		if(categoryId != null){
			Category c = new Category();
			c.setId(categoryId);
			film.setCategory(c);
		}
		return film;
	}

	@Override
	public Film findById(Integer id) {
		return filmDao.findByPk(id);
	}
}
